#include<iostream>
#include<unistd.h>
#include<cstdio>
#include<cstdlib>
#include<sys/types.h>
#include<errno.h>
#include<string.h>
#include<sys/wait.h>
using namespace std;

int main()
{
    pid_t id = fork();
    if(id < 0)
    {
        printf("errno: %d, errstring : %s\n", errno, strerror(errno));
        return errno;
    }
    else if(id == 0)//子进程
    {
        int cnt = 5;
        while(cnt)
        {
            printf("子进程运行中，pid:%d\n",getpid());
            cnt--;
            sleep(1);
        }

        exit(123);
    }
    else
    {
        pid_t rid = wait(nullptr);//wait函数。父进程等待子进程结束，成功会返回子进程的PID
        int status = 0;
        if(rid > 0)
        {
            if(WIFEXITED(status))//子程序正常终止
            {
                printf("wait sub process success, rid : %d, status code : %d\n",rid, WEXITSTATUS(status));//提取子进程退出码
            }
            else
            {
                printf("child process quit error!\n");
            }
        }
        else{
            perror("waitpid");
        }
        while(true)
        {
            printf("我是父进程，PID:%d\n",getpid());
            sleep(1);
        }
    }
    return 0;
}
